package com.ron.android.daneel;

import com.ron.provider.Daneel.Notes;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.ContentURI;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NoteEntry extends Activity {

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.note_entry);

		if( icicle != null ){
			populate( icicle.getString( Notes.TEXT ) );
		} else {
			if (getIntent().getAction().equals(Intent.EDIT_ACTION)) {
				ContentURI noteURI = getIntent().getData();
				populateFromDB( noteURI );
			} 
		}

		final Button okButton = (Button) findViewById(R.id.note_entry_ok_button);
		okButton.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				saveData(); 
				finish();
			}

		});

		final Button cancelButton = (Button) findViewById(R.id.note_entry_cancel_button);
		cancelButton.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	@Override
	protected void onFreeze(Bundle outState) {
		super.onFreeze(outState);
		EditText text = (EditText) findViewById(R.id.note_entry_text);
		String noteText = text.getText().toString(); 
		if( noteText.length() > 0 ){
			outState.putString(Notes.TEXT, noteText);
		}
	}

	private void populateFromDB( ContentURI noteURI ){
		
		Cursor noteCursor = managedQuery(noteURI,
				Notes.DEFAULT_PROJECTION, null, null);
		noteCursor.first();
		populate( noteCursor.getString(noteCursor
				.getColumnIndex(Notes.TEXT)) );		
	}
	
	private void populate(String noteText){
		EditText text = (EditText) findViewById(R.id.note_entry_text);
		text.setText(noteText);
	}
	
	private void saveData(){
		EditText text = (EditText) findViewById(R.id.note_entry_text);

		String noteText = text.getText().toString(); 
		if( noteText.length() > 0 ){
			ContentValues values = new ContentValues();
			values.put(Notes.TEXT, noteText);
	
			if ( getIntent().getAction().equals(Intent.INSERT_ACTION)) {
				getContentResolver().insert(Notes.CONTENT_URI, values);
			} else {
				getContentResolver().update(getIntent().getData(), values, null, null);
			}
		}
	}
	
}